// pages/goods/detail/index.js

import { reqGoodsInfo } from '@/api/good'
import { reqAddCart, reqCartList } from '@/api/cart'
import { userBehavior } from '@/behaviors/userBehavior'

Page({
  behaviors: [userBehavior],

  // 页面的初始数据
  data: {
    goodsInfo: {}, // 商品详情
    show: false, // 控制加入购物车和立即购买弹框的显示
    count: 1, // 商品购买数量，默认是 1
    blessing: '',// 祝福语
    buyNow: 0,//控制加入购物车还是立即购买  0 购物车 1购买
    allCount: '' //购物车总数量
  },
  onLoad(e) {
    this.getDetail(e.goodsId)
    this.getAllCount()
  },

  // 获取购物车总数量
  async getAllCount() {
    if (!this.data.token) return
    const { data } = await reqCartList()
    if (data.length < 1) return
    let allCount = 0
    data.forEach(item => {
      allCount += item.count
    })
    this.setData({
      allCount: allCount > 99 ? '99+' : allCount + ''
    })
  },

  async getDetail(id) {
    const { data } = await reqGoodsInfo(id)
    this.setData({
      goodsInfo: data
    })
  },
  // 加入购物车
  handleAddcart() {
    this.setData({
      show: true,
      buyNow: 0
    })
  },

  // 立即购买
  handeGotoBuy() {
    this.setData({
      show: true,
      buyNow: 1
    })
  },

  // 点击关闭弹框时触发的回调
  onClose() {
    this.setData({ show: false })
  },

  // 监听是否更改了购买数量
  onChangeGoodsCount(event) {
    console.log(event.detail)
    this.setData({
      count: Number(event.detail)
    })
  },

  // 预览
  previewFn() {
    wx.previewImage({
      urls: this.data.goodsInfo.detailList
    })
  },

  // 提交
  async handleSubmit() {
    const { token, count, blessing, buyNow } = this.data
    const goodsId = this.data.goodsInfo.id

    if (!token) {
      return wx.navigateTo({
        url: '/pages/login/login',
      })
    }

    if (+buyNow === 0) {
      // 购物车
      goodsId
      const res = await reqAddCart({ goodsId, count, blessing })
      if (res.code === 200) {
        wx.toast({ title: '加入购物车成功' })
        this.getAllCount()
        this.setData({
          show: false
        })
      }
    } else {
      // 立即购买
      wx.navigateTo({
        url: `/modules/orderPayModule/pages/order/detail/detail?goodsId=${goodsId}&blessing=${blessing}`
      })
    }

  }
})
